package de.tum.icuproject.persistence.couchdb.select;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import de.tum.icuproject.Subscriber;
import de.tum.icuproject.model.Session;

/**
 * Handles select session requests
 * @author stefanoturchetta
 *
 */
public class SelectSessionRequestHandler extends SelectRequestHandler {

	public SelectSessionRequestHandler(Subscriber subscriber) {
		super(subscriber);
	}

	@Override
	protected void onPostExecute(String result) {
		if (result != null) {
			Log.d("RESULT", result);
			Session session = this.deserializeResult(result);
			Subscriber subscriber = this.getSubscriber();
			subscriber.setCurrentSession(session);
		}
	}

	private Session deserializeResult(String result) {
		JsonParser parser = new JsonParser();
		JsonObject root = parser.parse(result).getAsJsonObject();
		JsonArray rows = root.get("rows").getAsJsonArray();
		// if there is nothing inside the array of possible json answers
		if (rows.size() == 0) {
			return null;
		}
		JsonObject firstObj = rows.get(0).getAsJsonObject();
		JsonObject value = firstObj.get("value").getAsJsonObject();
		Session session = new Gson().fromJson(value, Session.class);
		return session;
	}


}
